package tingshu.service;

import tingshu.data_object.AidToCountDO;
import tingshu.data_object.AlbumDO;
import tingshu.data_object.TrackDO;
import tingshu.repository.AlbumRepo;
import tingshu.repository.RelationRepo;
import tingshu.repository.TrackRepo;
import tingshu.util.Log;
import tingshu.view_object.AlbumResultView;
import tingshu.view_object.AlbumView;
import tingshu.view_object.BindView;
import tingshu.view_object.UserVO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author houdaiqin
 * @date 2022/07/17 15:26
 **/
public class AlbumService {
    private final AlbumRepo albumRepo=new AlbumRepo();
    private final RelationRepo relationRepo=new RelationRepo();
    private final TrackRepo trackRepo=new TrackRepo();

    public BindView getBindInfo(UserVO currentUser,int aid){
        //获取专辑信息（专辑id和专辑title）
        AlbumDO albumDO=albumRepo.selectOneByUidAndAid(currentUser.uid,aid);
        if(albumDO==null){
            throw new RuntimeException("aid 不存在或不属于这个用户");
        }

        //获取该专辑包含的音频id（tid）
        List<Integer> tidList=relationRepo.selectTidListByAid(aid);
        List<TrackDO> trackDOList;
        if(tidList.isEmpty()){
            trackDOList=new ArrayList<>();
        }else{
            //通过tid从数据库获取该音频的信息
            trackDOList=trackRepo.selectTrackListByTidList(tidList);
        }
        return new BindView(currentUser,albumDO,trackDOList);
    }

    public AlbumResultView getAlbumList(UserVO currentUser){
        AlbumResultView albumResultView=new AlbumResultView();

        //1.先获取该用户下所有的专辑id（aidList）
        List<Integer> aidList=albumRepo.selectAidListByUid(currentUser.uid);

        //2.用上一步获取的aid去数据库中查找每个专辑绑定的音频数
        List<AidToCountDO> aidToCountDOList=albumRepo.selectCountByAidListGroupByAidList(aidList);
        Log.println("查询relations表中的结果"+aidToCountDOList);

        //3.定义一个map，用来存储每个专辑以及专辑对应的音频数（专辑aid，每个专辑对应的音频数refCount）
        Map<Integer, Integer> aidToRefCountMap=new HashMap<>();
        for(AidToCountDO aidToCountDO:aidToCountDOList){
            aidToRefCountMap.put(aidToCountDO.aid, aidToCountDO.refCount);
        }
        Log.println("打印Map"+aidToRefCountMap);

        //4.查询出专辑的信息
        List<AlbumDO> albumDOList=albumRepo.selectAlbumListByUid(currentUser.uid);

        //5.AlbumDO ——> AlbumView
        List<AlbumView> albumViewList=new ArrayList<>();
        for(AlbumDO albumDO:albumDOList){
            AlbumView albumView=new AlbumView(albumDO,aidToRefCountMap.getOrDefault(albumDO.aid,0));
            albumViewList.add(albumView);
        }
        albumResultView.currentUser=currentUser;
        albumResultView.albumList=albumViewList;
        return albumResultView;
    }
}